﻿using NXDO.Data.Extension;
using NXDO.Data.Factory;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TDM.DbData.DataEntity;
using TDM.WebBase;

namespace TDM.WebBiz.TestData
{

    public class DataImportHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="importid"></param>
        /// <param name="isDeleteOld"></param>
        /// <returns></returns>
        public static void ImportData(long importid, bool isDeleteOld)
        {
            try
            {
                var data = Get(importid);
                if (data == null) throw new Exception("该导入数据记录有误");
                //解压缩
                string basePath = BasePathHelper.GetDataImportPath();
                var zipFile = Path.Combine(basePath, data.FilePath);
                var zipTempFile = Path.Combine(basePath, data.FilePath) + ".tmp";
                string dateFlag = DateTime.Now.ToString("yyyyMMddHHmmss");
                //解密
                var stream = WebBase.AES_EnorDecrypt.DecpStream(zipFile);
                using (var fs = File.Create(zipTempFile))
                {
                    stream.CopyTo(fs);
                }
                //解压缩
                ZipFile.ExtractToDirectory(zipTempFile, Path.Combine(basePath, dateFlag));
                string DataCSV = Path.Combine(basePath, dateFlag, "DataExport.csv");
                if (!File.Exists(DataCSV)) throw new Exception("导入的数据包有错误,缺少必须的文件");

                var line = File.ReadLines(DataCSV).First();
                string[] datas = line.Split(new char[] { ',' });
                //更新数据
                data.ExportTime = Convert.ToDateTime(datas[1]);
                data.ExportRepOffice = datas[4];
                data.ExportType = Convert.ToInt16(datas[3]);
                data.DBLinq().ToCommand(data).Update();
                File.Delete(DataCSV);
                //执行导入
                NXDO.Data.DbClient.Transfer.BulkImport.GetImportWithDirectory(isDeleteOld, Path.Combine(basePath, dateFlag)).Execute();
                data.IsImport = true;
                data.DBLinq().ToCommand(data).Update();
            }
            catch (Exception)
            {

                throw;
            }

        }

        public static DataImport Get(long importid)
        {
            string sqltxt = "select * from DataImport where importid={0}";
            var rs = DbHelper.SetCommand(sqltxt, importid).ExecuteEntityScalar<DataImport>();
            return rs;
        }

    }
}
